﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using Core;
using Core.ChannelProtocol;
using Core.DeviceProtocol;
using Core.Helper;
using Core.Model;
using Core.Msg;
using log4net;

namespace TcpClientChannel
{
    public sealed class TcpClientChannel : BaseChannel
    {
        private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private Thread _channelThread;
        private bool _running;
        private bool _connected = true;
        private TcpClient _client { get; set; }
        private IPEndPoint _endPoint { get; }
        private readonly Queue<RxTxCommand> _sendCommands = new Queue<RxTxCommand>();
        private readonly Queue<RxTxCommand> _insertCommands = new Queue<RxTxCommand>();
       
        public TcpClientChannel(Channel channel)
        {
            try
            {
                ChlInfo = channel;
                ChlInfo.PollingDelay = channel.PollingDelay < 5 ? 5 : channel.PollingDelay;
                _endPoint = new IPEndPoint(IPAddress.Parse(ChlInfo.Ip), ChlInfo.Port);
                List<Device> devices = Global.DataAccess.GetDevices(ChlInfo.Id);
                if (devices != null)
                {
                    foreach (Device dev in devices)
                    {
                        LoadProtocol(dev);
                    }
                }
            }
            catch
            {
            }
        }

        private void ThreadProc()
        {
            while (Running)
            {
                if (_sendCommands.Count > 0 || _insertCommands.Count > 0)
                {
                    if (!Connected)
                        Connect();
                    if (_client == null || !_client.Connected)
                    {
                        Thread.Sleep(2000);
                        _sendCommands.Clear();
                        _insertCommands.Clear();
                        continue;
                    }
                    try
                    {
                        RxTxCommand cmd;
                        if (_insertCommands.Count > 0)
                        {
                            cmd = _insertCommands.Dequeue();
                        }
                        else
                        {
                            cmd = _sendCommands.Dequeue();
                        }

                        if (cmd != null)
                        {
                            Write(cmd, _client);
                            Read(cmd, _client);
                            RaiseMessageEvent(cmd);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Info(ex.Message);
                    }
                }
                else
                {
                    NextDevice();
                    CurDevProtocol?.RunPolling();
                }
                Thread.Sleep(ChlInfo.PollingDelay);
            }
        }
       
        public override bool Connected
        {
            get
            {
                bool temp = false;
                if (_client != null)
                {
                    var state = _client.GetState();
                    temp  = state == TcpState.Established;
                }
                if (!temp.Equals(_connected))
                {
                    _connected = temp;
                }
                if (!_connected)
                {
                    foreach (KeyValuePair<string, BaseDevProtocol> devProtocol in protocols)
                    {
                        devProtocol.Value.Dev.IsConnected = false;
                        devProtocol.Value.DataItems.ForEach(sss => sss.CurValue = 0);
                    }
                }
                return _connected;
            }
        }
        public override bool Running
        {
            get
            {
                return _running;
            }
            set
            {
                if (!_running.Equals(value))
                {
                    _running = value;
                }
            }
        }
        public override bool Start()
        {

            try
            {
                Running = false;
                if (!Connected)
                {
                    Stop();
                   Connect(true);
                    _channelThread = new Thread(ThreadProc);
                    _channelThread.IsBackground = true;
                    Running = true;
                    _channelThread.Start();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return false;
            }
            return true;
        }

        public override void Stop()
        {
            try
            {
                Running = false;
                _channelThread?.Abort();
                base.Stop();
            }
            catch //(Exception e)
            {
                //_log.Error(e.Message);
            }
        }

        protected override bool Connect(bool log = false)
        {
            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;
            bool result = false;
            var t = System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    _client = new TcpClient();
                    _client.SendTimeout = ChlInfo.WriteTimeout;
                    _client.ReceiveTimeout = ChlInfo.ReadTimeout;
                    _client.Connect(_endPoint);
                    result = true;
                }
                catch //(Exception ex)
                {
                   
                }
            }, token);
            if (!t.Wait(1500, token)) // 等待1.5秒 避免Socket等待超时太长
            {
                tokenSource.Cancel();
            }
            if (result)
            {
                if (!log)  // 提示重新连接成功
                    _log.Info("通道连接成功:" + ChlInfo.Name);
            }
            else
            {
                if (log)
                    _log.Error("通道连接失败:" + ChlInfo.Name);
            }
            return result;
        }

        public override void PutCommand(RxTxCommand cmd)
        {
            if (cmd != null)
            {
                _sendCommands.Enqueue(cmd, 100);
            }
        }

        public override void PutInsertCommand(RxTxCommand cmd)
        {
            if (cmd != null)
            {
                _sendCommands.Enqueue(cmd, 100);
            }
        }

        public override RxTxCommand PostToExcute(string devId, string operId)
        {
            if (protocols.ContainsKey(devId))
            {
                RxTxCommand cmd = protocols[devId].PostToExcute(operId);
                PutCommand(cmd);
                return cmd;
            }
            return null;
        }

        public override RxTxCommand PostToExcute(string devId, string operId, string[] paras)
        {
            if (protocols.ContainsKey(devId))
            {
                RxTxCommand cmd = protocols[devId].PostToExcute(operId, paras);
                PutCommand(cmd);
                return cmd;
            }
            return null;
        }

        private bool Write(RxTxCommand cmd,TcpClient client)
        {
            if (cmd == null)
            {
                return false;
            }
            try
            {
                cmd.SendTime = DateTime.Now;
                client.NoDelay = true;
                byte[] bytes = cmd.SendBytes;

                if (bytes != null && bytes.Length > 0)
                {
                    client.SendTimeout = cmd.Timeout;
                    NetworkStream stream = client.GetStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();
                    return true;
                }
            }
            catch (Exception ex)
            {
                if (!Connected)
                    Connect();
                _log.Error(ex.Message);
            }
            return false;
        }

        private void Read(RxTxCommand cmd, TcpClient client)
        {
            if (cmd.NeedReply)
            {
                try
                {
                    client.ReceiveTimeout = cmd.Timeout;
                    NetworkStream stream = client.GetStream();
                    byte[] buffer = new byte[1500];
                    int len = stream.Read(buffer, 0, buffer.Length);
                    List<byte> tempbuffer = new List<byte>();
                    int count = 3;
                    while (len > 0)
                    {
                        byte[] bytes = new byte[len];
                        Buffer.BlockCopy(buffer, 0, bytes, 0, len);
                        tempbuffer.AddRange(bytes);
                        count--;
                        if (count <= 0)
                            break;
                        try
                        {
                            len = stream.Read(buffer, 0, buffer.Length);
                        }
                        catch
                        {
                            len = -1;
                        }
                    }
                    cmd.ReceiveBytes = tempbuffer.ToArray();
                    if (cmd.ReceiveResult == MsgResult.RecTimeout || cmd.ReceiveResult == MsgResult.Undefined)
                    {
                        if (CurDevProtocol != null && CurDevProtocol.Dev.Id == cmd.DeviceId)
                        {
                            if (CurDevProtocol.Dev.BreakCount < CurDevProtocol.Dev.BreakOff)
                            {
                                CurDevProtocol.Dev.BreakCount++;
                                if (CurDevProtocol.Dev.BreakCount == CurDevProtocol.Dev.BreakOff)
                                {
                                    CurDevProtocol.DataItems.ForEach(sss => sss.CurValue = 0);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (CurDevProtocol != null && CurDevProtocol.Dev.Id == cmd.DeviceId)
                        {
                            CurDevProtocol.Dev.BreakCount = 0;
                        }
                    }
                }
                catch //(Exception ex)
                {
                    if (CurDevProtocol != null && CurDevProtocol.Dev.Id == cmd.DeviceId)
                    {
                        if (CurDevProtocol.Dev.BreakCount < CurDevProtocol.Dev.BreakOff)
                            CurDevProtocol.Dev.BreakCount++;
                    }
                    //_log.Error("操作反馈异常:" + ex.Message);
                }
            }
        }

    }
}
